<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="openCreateDrawer(true)">
            <template #icon>
              <n-icon>
                <PlusOutlined/>
              </n-icon>
            </template>
            添加用户
          </n-button>
          <n-button type="primary" @click="handleImport" class="ml-2">
            <template #icon>
              <n-icon>
                <UploadOutlined/>
              </n-icon>
            </template>
            导入用户
          </n-button>
          <n-button type="primary" @click="exportUser" class="ml-2">
            <template #icon>
              <n-icon>
                <DownloadOutlined/>
              </n-icon>
            </template>
            导出用户
          </n-button>
        </template>

        <template #action>
          <TableAction/>
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          checkable
          :virtual-scroll="true"
          :key-field="'id'"
          :label-field="'name'"
          :data="treeData"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
    <CreateDrawer ref="createDrawerRef"/>
    <Upload ref="uploaderRef"/>
  </div>
</template>

<script lang="ts" setup>
import {h, inject, onMounted, reactive, ref, unref} from 'vue';
import {useDialog, useMessage} from 'naive-ui';
import {BasicTable, TableAction} from '@/components/Table';
import {BasicForm, FormSchema, useForm} from '@/components/Form/index';
import {columns} from './columns';
import {PlusOutlined, UploadOutlined, DownloadOutlined} from '@vicons/antd';
import {getTreeAll} from '@/utils';
import {useRouter} from 'vue-router';
import CreateDrawer from './CreateDrawer.vue';
import Upload from "./upload.vue";
import {delUser, editUser, getUserList} from "@/api/system/user";
import {getRoleList} from "@/api/system/role";
import axios from "axios";
import {useUserStore} from "@/store/modules/user";

const reloadPage = inject('reloadPage') as Function;

const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'NInput',
    label: '姓名',
    componentProps: {
      placeholder: '请输入姓名',
      onInput: (e: any) => {
        searchForm.value.name = e;
      },
    },
  },
  {
    field: 'dept',
    component: 'NInput',
    label: '部门',
    componentProps: {
      placeholder: '请输入部门',
      onInput: (e: any) => {
        searchForm.value.dept = e;
      },
    },
  },
  {
    field: 'telephone',
    component: 'NInput',
    label: '手机号',
    componentProps: {
      placeholder: '请输入手机号码',
      onInput: (e: any) => {
        searchForm.value.telephone = e;
      },
    },
  },
  {
    field: 'valid',
    component: 'NSelect',
    label: '是否有效',
    componentProps: {
      placeholder: '请选择类型',
      options: [
        {
          label: '有效',
          value: 1,
        },
        {
          label: '无效',
          value: 0,
        },
      ],
      onUpdateValue: (e: any) => {
        searchForm.value.valid = e;
      },
    },
  },
];

const router = useRouter();
const message = useMessage();
const userStore = useUserStore();
const actionRef = ref();
const createDrawerRef = ref();
const uploaderRef = ref();

const dialog = useDialog();
const showModal = ref(false);
const formBtnLoading = ref(false);
const checkedAll = ref(false);
const editRoleTitle = ref('');
const treeData = ref([]);
const expandedKeys = ref([]);
const checkedRecordId = ref('');
const checkedKeys = ref([]);

const defaultValueRef = () => ({
  name: undefined,
  dept: undefined,
  telephone: undefined,
  valid: null,
});

const searchForm = ref(defaultValueRef())

const params = reactive({
  pageSize: 10,
});

const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '角色列表',
          onClick: handleMenuAuth.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['role_menu_list'],
        },
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
          auth: ['role_edit'],
        },
        {
          label: '删除',
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['role_del'],
        },
      ],
    });
  },
});

const [register, {getFieldsValue}] = useForm({
  gridProps: {cols: '1 s:1 s:2 s:3 s:4 s:5'},
  labelWidth: 80,
  showAdvancedButton: false,
  schemas,
});

const loadDataTable = async (params: any) => {
  params = {
    ...params,
    ...searchForm.value,
  }
  const response = await getUserList(params)
  return response.data;
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function openCreateDrawer(isInit: boolean = false) {
  createDrawerRef.value.openDrawer(isInit);
}

function reloadTable() {
  actionRef.value.reload();
}

function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  setTimeout(() => {
    editUser({
      id: checkedRecordId.value,
      role_list: checkedKeys.value,
    }).then(res => {
      if (res.code === 200) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      showModal.value = false;
      reloadTable();
      formBtnLoading.value = false;
    })

  }, 200);
}

function handleEdit(record: Recordable) {
  Object.assign(createDrawerRef.value.formParams, record);
  if (null != createDrawerRef.value.formParams.valid) {
    createDrawerRef.value.formParams.valid = createDrawerRef.value.formParams.valid.toString()
  }
  createDrawerRef.value.rules.password.required = false;
  openCreateDrawer(false);
}

function handleDelete(record: Recordable) {
  dialog.info({
    title: '提示',
    content: `您确定想删除此用户吗?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      delUser(record.id).then(res => {
        if (res.code === 200) {
          message.success('删除成功', {
            duration: 1000,
            closable: true,
          });
          reloadPage();
        } else {
          message.error(res.message, {
            duration: 1000,
            closable: true,
          });
        }
      })
    },
    onNegativeClick: () => {
      message.error('已取消');
    },
  });
}

function handleSubmit(values: Recordable) {
  actionRef.value.updatePage(1);
}

function handleReset(values: Recordable) {
  Object.assign(searchForm.value, defaultValueRef())
}

function handleMenuAuth(record: Recordable) {
  editRoleTitle.value = `分配 ${record.name} 的用户角色`;
  checkedRecordId.value = record.id;
  checkedKeys.value = record.role_list;
  showModal.value = true;
}

function checkedTree(keys) {
  checkedKeys.value = keys;
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}

function packHandle() {
  let keys = []
  if (!expandedKeys.value.length) {
    keys = packAllKey(unref(treeData))
  }
  expandedKeys.value = keys
}

function packAllKey(listData: any[]) {
  return listData.map((item: any) => item.id as number) as []
}

function checkedAllHandle() {
  if (!checkedAll.value) {
    checkedKeys.value = [...getTreeAll(treeData.value)] as [];
    checkedAll.value = true;
  } else {
    checkedKeys.value = [];
    checkedAll.value = false;
  }
}

const handleImport = () => {
  uploaderRef.value.showUploader = true;
}

async function exportUser() {
  try {
    let res = await axios.post('/api/user/export', params, {
      baseURL: import.meta.env.VITE_GLOB_API_URL, // 指定服务器地址
      responseType: 'blob',
      headers: {
        Authorization: userStore.getToken,
      }
    });
    // 获取http头部的文件名信息，若无需重命名文件，将下面这行删去
    // const fileName = res.headers["content-disposition"].split("=")[1];
    const fileName = '人员列表';
    /* 兼容ie内核，360浏览器的兼容模式 */
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      const blob = new Blob([res.data], {
        type: res.headers['content-type']
      });
      window.navigator.msSaveOrOpenBlob(
        blob,
        decodeURIComponent(fileName)
      );
    } else {
      /* 火狐谷歌的文件下载方式 */
      const blob = new Blob([res.data], {
        type: res.headers['content-type']
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a"); // 创建a标签
      link.href = url;
      link.download = decodeURIComponent(fileName); // 文件重命名，若无需重命名，将该行删去
      link.click();
      URL.revokeObjectURL(url); // 释放内存
    }
  } catch (error) {
    console.error(error);
  }
}

onMounted(async () => {
  const treeMenuList = await getRoleList({_all: 1});
  treeData.value = treeMenuList.data.list;
  expandedKeys.value = packAllKey(unref(treeData))
});
</script>

<style lang="less" scoped></style>
